﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Subjects;
using System.Reactive.Linq;
using System.Threading;
using System.Windows.Forms;

namespace Demo
{
	public partial class WebRequestExampleForm : Form
	{
		private List<string> _messages;
		public WebRequestExampleForm()
		{
			InitializeComponent();
			_messages = new List<string>();
		}


		private void longRunningProcessBtn_Click(object sender, EventArgs e)
		{
			PostMessage("starting long running activity");
            _messages.Clear();

			//Start will launch the process immediately on a separate thread
			var longProcess = Observable.Start(() => LongRunningActivity("param"));

			//optional subscription - this is only necessary if you want completion notification
			longProcess.ObserveOn(listBox1).Subscribe(
				x => listBox1.Items.Add("OnNext"),
				err => listBox1.Items.Add("Error " + err.Message),
				() => listBox1.Items.Add("OnComplete"));

			PostMessage("Continuing to work...");
		}
		private void LongRunningActivity(string pParam)
		{
			//if UI updating is necessary, try Prism's EventAggregator to send text via message
			_messages.Add(DateTime.Now + " starting");
			Thread.Sleep(5000);
			_messages.Add(DateTime.Now + " ending");
		}


		private void multipleLongRunningProcessBtn_Click(object sender, EventArgs e)
		{
            //create a cold stream of values to process
            var lst = new List<string>();
            lst.Add("http://www.reddit.com/");
            lst.Add("http://www.yahoo.com/");
            lst.Add("http://www.microsoft.com/");
		   
			//for cold stream, subscription is necessary to launch
            lst.ToObservable().ObserveOn(listBox1).Subscribe(
				url => ProcessUrl(url),
				err => PostMessage("OnError"),
				() => PostMessage("Complete"));

		}



		private void PostMessage(string msg)
		{
			listBox1.Items.Add(DateTime.Now + " - " + msg);
			Application.DoEvents();			
		}

		public void ProcessUrl(string pUrl)
		{
			PostMessage("starting to process url " + pUrl);
			Thread.Sleep(3000);
			PostMessage("ending processing url " + pUrl);
		}

		private void button2_Click(object sender, EventArgs e)
		{
			listBox1.Items.AddRange(_messages.ToArray());
		}
	}

}